package com.cuixichang.minimalism.acl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.cuixichang.minimalism.basal.base.Validate;
import com.cuixichang.minimalism.basal.enums.IsEnableEnum;
import com.cuixichang.minimalism.basal.enums.SubassemblyTypeEnum;
import com.cuixichang.minimalism.basal.utils.RegexValidateUtil;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.Objects;
import java.util.Optional;
import java.util.function.BiFunction;
import java.util.stream.Collectors;

@Component
public class DateTimeIntervalSubassemblyDesign extends SubassemblyDesignAbs{
    @Override
    public SubassemblyTypeEnum getType() {
        return SubassemblyTypeEnum.DateTimeInterval;
    }

    @Override
    public Validate structureValidate(String structure) {
        return Validate.builder().checked(true).message(IsEnableEnum.YES.getDesc()).build();
    }

    @Override
    public Validate valueValidate(String structure, String value) {
        boolean pass = JSONUtil.isJsonArray(value);
        if(pass){
            JSONArray objects = JSONUtil.parseArray(value);
            pass = objects.size()==2;
            if(pass){
                pass = RegexValidateUtil.checkDateTime(objects.get(0,String.class)) &&
                        RegexValidateUtil.checkDateTime(objects.get(1,String.class));
            }
        }
        return Validate.builder().checked(pass).message(pass ? IsEnableEnum.YES.getDesc():"日期值格式检验不通过").build();
    }

    @Override
    public String previewValue(String structure, Object value) {
        String key = Objects.isNull(value)? StrUtil.EMPTY:String.valueOf(value);
        Validate validate = valueValidate(structure, key);
        if(Objects.nonNull(validate) && validate.getChecked()){
             JSONArray objects = JSONUtil.parseArray(value);
             return objects.get(0,String.class).concat(StrUtil.DASHED).concat(objects.get(1,String.class));
        }
        return StrUtil.EMPTY;
    }

    @Override
    public Object resultValue(String value) {
      return Optional.ofNullable(value).map(JSONUtil::parseArray).map(jsonArray -> jsonArray.stream()
                    .map(Object::toString).collect(Collectors.toList())).orElse(Collections.emptyList());
    }

    @Override
    public String resultValue(Object value) {
        return JSONUtil.toJsonStr(value);
    }
}
